import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class ErrorProblemsPage extends StatefulWidget {
  @override
  _ErrorProblemsPageState createState() => _ErrorProblemsPageState();
}

class _ErrorProblemsPageState extends State<ErrorProblemsPage> {
  List<dynamic> errorProblems = [];

  @override
  void initState() {
    super.initState();
    fetchErrorProblems();
  }

  Future<void> fetchErrorProblems() async {
    const url = 'http://101.34.58.190:8080/error-problems?userId=1';

    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        setState(() {
          errorProblems = data['errorProblems'] ?? [];
        });
      } else {
        print('Failed to load error problems: ${response.statusCode}');
      }
    } catch (e) {
      print('Error occurred while fetching error problems: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('错题本'),
        backgroundColor: Colors.lightBlueAccent,
      ),
      body: errorProblems.isEmpty
          ? const Center(
        child: CircularProgressIndicator(),
      )
          : ListView.builder(
        itemCount: errorProblems.length,
        itemBuilder: (context, index) {
          final problem = errorProblems[index];
          return Card(
            margin: const EdgeInsets.all(8.0),
            elevation: 4.0,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '题目: ${problem['express']}',
                    style: const TextStyle(
                        fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 8),
                  Text('你的答案: ${problem['userAns'] ?? '未作答'}',
                      style: const TextStyle(fontSize: 14, color: Colors.red)),
                  const SizedBox(height: 4),
                  Text('正确答案: ${problem['realAns']}',
                      style: const TextStyle(fontSize: 14, color: Colors.green)),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
